/*
Copyright (c) 2008  Franklin Schmidt <fschmidt@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package fschmidt.util.java;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;


public final class IoUtils {
	private IoUtils() {}  // never

	private static final int bufSize = 8192;

	public static String readAll(Reader in)
		throws IOException
	{
		char[] a = new char[bufSize];
		StringBuilder buf = new StringBuilder();
		int n;
		while( (n=in.read(a)) != -1 ) {
			buf.append(a,0,n);
		}
		return buf.toString();
	}

	public static void copyAll(InputStream in,OutputStream out)
		throws IOException
	{
		byte[] a = new byte[bufSize];
		int n;
		while( (n=in.read(a)) != -1 ) {
			out.write(a,0,n);
		}
	}

	public static int copyAllAndCount(InputStream in,OutputStream out)
		throws IOException
	{
		byte[] a = new byte[bufSize];
		int n;
		int count = 0;
		while( (n=in.read(a)) != -1 ) {
			out.write(a,0,n);
			count += n;
		}
		return count;
	}

	public static void copyAvailable(InputStream in,OutputStream out)
		throws IOException
	{
		byte[] a = new byte[bufSize];
		while( in.available() > 0 ) {
			out.write(a,0,in.read(a));
		}
	}

	public static byte[] readAll(InputStream in)
		throws IOException
	{
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		copyAll(in,out);
		return out.toByteArray();
	}

	public static void writeAll(byte[] a,OutputStream out)
		throws IOException
	{
		copyAll(new ByteArrayInputStream(a),out);
	}

	public static byte[] readAll(File file)
		throws IOException
	{
		int len = (int)file.length();
		ByteArrayOutputStream out = new ByteArrayOutputStream(len) {
			public byte[] toByteArray() {
				return buf;
			}
		};
		FileInputStream in = new FileInputStream(file);
		copyAll(in,out);
		in.close();
		return out.toByteArray();
	}

	public static void writeAll(byte[] a,File file)
		throws IOException
	{
		FileOutputStream fos = new FileOutputStream(file);
		writeAll(a,fos);
		fos.close();
	}

	public static String readPage(String url)
		throws IOException
	{
		return new UrlCall(url).get();
	}

	public static String read(URL url)
		throws IOException
	{
		return new UrlCall(url).get();
	}

	public static String post(String urlS,String postS)
		throws IOException
	{
		return new UrlCall(urlS).post(postS);
	}

	public static String hideNull(String s) {
		return s==null ? "" : s;
	}

	public static boolean delete(File file) {
		if( file.isDirectory() ) {
			File[] files = file.listFiles();
			for( int i=0; i<files.length; i++ ) {
				delete(files[i]);
			}
		}
		return file.delete();
	}

	public static URL getUrlFromResource(String resourceName) {
/*
		ClassLoader loader = IoUtils.class.getClassLoader();
		return loader.getResource(resourceName);
*/
		return ClassLoader.getSystemResource(resourceName);
	}

	public static String getContentFromResource(String resourceName)
		throws IOException
	{
		URL url = getUrlFromResource(resourceName);
		return url==null ? null : read(url);
	}

	public static String read(File file)
		throws IOException
	{
		Reader in = newFileReader(file);
		String s = readAll(in);
		in.close();
		return s;
	}

	public static void write(File file,String s)
		throws IOException
	{
		Writer out = newFileWriter(file);
		out.write(s);
		out.close();
	}

	public static Reader newFileReader(File file)
		throws IOException
	{
		return new InputStreamReader(new FileInputStream(file),Charset.forName("utf-8"));
	}

	public static Reader newFileReader(String file)
		throws IOException
	{
		return new InputStreamReader(new FileInputStream(file),Charset.forName("utf-8"));
	}

	public static Writer newFileWriter(File file)
		throws IOException
	{
		return new OutputStreamWriter(new FileOutputStream(file),Charset.forName("utf-8"));
	}

	public static Writer newFileWriter(String file)
		throws IOException
	{
		return new OutputStreamWriter(new FileOutputStream(file),Charset.forName("utf-8"));
	}

	public static int hashCode(InputStream in)
		throws IOException
	{
		int h = 0;
		int c;
		while( (c=in.read()) != -1 ) {
			h = 31*h + c;
		}
		return h;
	}

	public static int hashCode(File file)
		throws IOException
	{
		InputStream in = new BufferedInputStream(new FileInputStream(file));
		int r = hashCode(in);
		in.close();
		return r;
	}

	public static int compare(InputStream in1,InputStream in2)
		throws IOException
	{
		while(true) {
			int c1 = in1.read();
			int c2 = in2.read();
			if( c1 == -1 && c2 == -1 )
				return 0;
			if( c1 != c2 )
				return c1 - c2;
		}
	}

	public static int compare(File file1,File file2)
		throws IOException
	{
		InputStream in1 = new BufferedInputStream(new FileInputStream(file1));
		InputStream in2 = new BufferedInputStream(new FileInputStream(file2));
		int r = compare(in1,in2);
		in2.close();
		in1.close();
		return r;
	}

	public static void copy(File file1,File file2)
		throws IOException
	{
		InputStream in = new BufferedInputStream(new FileInputStream(file1));
		OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
		copyAll(in,out);
		out.close();
		in.close();
	}

	public static Iterable<URL> getResources(Class classInJarOrDir) {
		String classFile = classInJarOrDir.getName().replace('.','/') + ".class";
		return getResources(classFile);
	}

	public static Iterable<URL> getResources(String fileName) {
		URL classUrl = ClassLoader.getSystemResource(fileName);
		String protocol = classUrl.getProtocol();
		if( protocol.equals("file") ) {
			File f = new File(classUrl.getFile()).getParentFile();
			for( int i = -1; (i = fileName.indexOf('/',i+1)) != -1; ) {
				f = f.getParentFile();
			}
			return new FileIterator(f);
		}
		if( protocol.equals("jar") ) {
			String s = classUrl.getFile();
			if( !s.startsWith("file:") )
				throw new RuntimeException("jar isn't file: "+classUrl);
			File f = new File(s.substring(5,s.indexOf('!')));
			try {
				JarFile jar = new JarFile(f);
				return new JarIterator(jar);
			} catch(IOException e) {
				throw new RuntimeException(e);
			}
		}
		throw new RuntimeException("can't handle protocol: "+protocol);
	}

	private static class FileIterator implements Iterator<URL>, Iterable<URL> {
		private final File[] files;
		private Iterator<URL> childIter = Collections.<URL>emptyList().iterator();
		private URL next;
		private int i = -1;

		FileIterator(File dir) {
			this.files = dir.listFiles();
		}

		public Iterator<URL> iterator() {
			return this;
		}

		public boolean hasNext() {
			if( next!=null )
				return true;
			if( childIter.hasNext() ) {
				next = childIter.next();
				return true;
			}
			while( ++i < files.length ) {
				File f = files[i];
				if( f.isFile() ) {
					try {
						next = f.toURL();
					} catch(MalformedURLException e) {
						throw new RuntimeException(e);
					}
					return true;
				}
				if( f.isDirectory() ) {
					childIter = new FileIterator(f);
					if( childIter.hasNext() ) {
						next = childIter.next();
						return true;
					}
				}
			}
			return false;
		}

		public URL next() {
			if( next==null )
				throw new NoSuchElementException();
			try {
				return next;
			} finally {
				next = null;
			}
		}

		public void remove() {
			throw new UnsupportedOperationException();
		}
	}

	private static class JarIterator implements Iterator<URL>, Iterable<URL> {
		private final Enumeration<JarEntry> entries;
		private final String urlBase;

		JarIterator(JarFile jar) {
			this.entries = jar.entries();
			try {
				this.urlBase = "jar:" + new File(jar.getName()).toURL().toString() + "!/";
			} catch(MalformedURLException e) {
				throw new RuntimeException(e);
			}
		}

		public Iterator<URL> iterator() {
			return this;
		}

		public boolean hasNext() {
			return entries.hasMoreElements();
		}

		public URL next() {
			try {
				return new URL( urlBase + entries.nextElement() );
			} catch(MalformedURLException e) {
				throw new RuntimeException(e);
			}
		}

		public void remove() {
			throw new UnsupportedOperationException();
		}
	}

}
